"""
    Author:
    Date: 2019-11-28

    砸蛋管理类
"""

from utils import db


def get_max_egg_set(egg_type):
    """ 获取砸蛋信息 """
    sql = f'''
        SELECT      MAX(set_id) AS max_set_id
        FROM        cmf_config_game_egg
        WHERE       egg_type={egg_type};
    '''
    data = db.query_data_from_db(sql)
    return data[0]['max_set_id'] if data else 0


def get_egg_config(set_id, egg_type):
    """ 获取砸蛋信息 """
    sql = f'''
        SELECT      e.gift_id,
                    e.gift_count,
                    e.prob,
                    g.name AS gift_name
        FROM        cmf_config_game_egg AS e
        JOIN        cmf_config_gift AS g ON g.id = e.gift_id
        WHERE       e.set_id={set_id} AND
                    e.egg_type={egg_type};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_egg_gift_probability(egg_type):
    """ 获取砸蛋的礼物概率 """
    set_id = get_max_egg_set(egg_type)
    items = get_egg_config(set_id, egg_type)
    total_count = sum([x['gift_count'] for x in items])

    gifts = []
    for item in items:
        gift_name = item['gift_name']
        gift_prob = '%.3f%%' % (100*item['gift_count']/total_count if total_count > 0 else 0)
        gifts.append((gift_name, gift_prob))
    gifts.sort(key=lambda x: x[1], reverse=False)
    return gifts


def get_egg_gift_display_probability(egg_type):
    """ 获取砸蛋的礼物外显概率 """
    set_id = get_max_egg_set(egg_type)
    items = get_egg_config(set_id, egg_type)

    gifts = []
    for item in items:
        gift_name = item['gift_name']
        gift_prob = item['prob']
        gifts.append((gift_name, gift_prob))
    gifts.sort(key=lambda x: x[1], reverse=False)
    return gifts


if __name__ == '__main__':
    print('ok')

